import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/home.vue"),
    meta: {
      title: "首页",
    },
  },
  {
    path: "/find",
    name: "find",
    component: () => import("../views/find.vue"),
    meta: {
      title: "发现",
    },
    beforeEnter: (to, from, next) => {
      console.log(localStorage.getItem("findType"));
      // console.log(to);
      if (to.fullPath === "/find") {
        console.log(from);
        next({
          path: "/find",
          query: {
            type: localStorage.getItem("findType")
              ? localStorage.getItem("findType")
              : "专题",
          },
        });
      } else next();
    },
  },
  {
    path: "/read",
    name: "read",
    component: () => import("../views/read.vue"),
    meta: {
      title: "连载",
    },
  },
  {
    path: "/personal",
    name: "personal",
    component: () => import("../views/personal.vue"),
    meta: {
      title: "个人中心",
    },
  },
  {
    path: "/search",
    name: "search",
    component: () => import("../views/search.vue"),
    meta: {
      title: "搜索",
    },
  },
  {
    path: "/publish",
    name: "publish",
    component: () => import("../views/publish.vue"),
    meta: {
      title: "发布",
    },
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login.vue"),
    meta: {
      title: "登入",
    },
  },
  {
    path: "/edit",
    name: "edit",
    component: () => import("../views/personal/editPersonal.vue"),
    meta: {
      title: "编辑个人信息",
    },
  },
  {
    path: "/readview",
    name: "readview",
    component: () => import("../views/readView.vue"),
    meta: {
      title: "阅读展示",
    },
  },
];

const router = createRouter({
  // 指定路由模式
  history: createWebHistory(),
  // 路由地址
  routes: routes,
});
// 全局守卫
// 前置守卫————执行前，一般验证用户是否登入，token验证
router.beforeEach((to, from, next) => {
  // console.log(localStorage.getItem('phone'));
  document.title = "一个" + "——" + to.meta.title; //设置当前页的title
  // console.log(to.matched);
  if (localStorage.getItem("phone")) {
    next();
  } else {
    if (to.name === "login") {
      //防止next无限循环的问题
      next();
    } else next({ path: "/login" });
  }
});

export default router;
